<?php defined('SYSPATH') or die('No direct script access.');

class Model_Review_Otzovik extends Model_Review_Abstract
{ 
    protected $_table_name = 'otzovik_reviews';  
    
    public function get_entity()
    {
        return 'otzovik';
    }
    
    public function get_reviews_query($entity)
    {
        // Если ищем по товару или модели
        if ($entity instanceof Model_Product) {
            $model_id = $entity->model_id; 
        } else if ($entity instanceof Model_Model) {
            $model_id = $entity->id;
        } else {
            throw new Model_Exception('Некорректный тип');
        }
        return DB::select(
                array(DB::expr('\'otzoviik\''), 'entity'),
                'id',
                'model_id',
                'source_id',
                'user_nick',
                'user_link',
                'rating',
                array(DB::expr('NULL'), 'experience'), 
                'pluses',
                'minuses',
                'text',
                'link',
                'date',
                'usefulness',
                'u_yes',
                'u_no'
            )
            ->from($this->_table_name)
            ->where('model_id', '=', $model_id);
    }
    
    public function add_review(Model_Model $model, $source_id, $text, $pluses, $minuses, $rating,
        $user_nick, $user_link, $link, $date, $u_yes, $u_no)
    {
        $this->model_id = $model->id;
        $this->source_id = $source_id;
        $this->text     = $text;
        $this->pluses   = $pluses;
        $this->minuses  = $minuses;
        $this->rating   = $rating;
        $this->user_nick = $user_nick;
        $this->user_link = $user_link;
        $this->link     = $link;
        $this->date     = $date;
        $this->u_yes    = $u_yes;
        $this->u_no     = $u_no;
        $this->usefulness = $this->get_usefulness();
		
		try {
			$this->save();
			
			$model->change_count_reviews();
			if ($rating) {
				$model->change_count_stars($rating);
			}
		} catch (Database_Exception $e) {
			if (strstr($e->getMessage(), 'Duplicate entry') !== false) {
				return null;
			}
			die($e->getMessage());
		}
        
        return $this;  
    }    
}